﻿using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web.Mvc;

namespace Ndex.Core.Service
{
    [DataContract]
    public class ServiceResponse : ServiceMessage
    {
        #region Constructors

        public ServiceResponse()
        {
            Message = string.Empty;
            Errors = new List<ValidationModel>();
        }

        public ServiceResponse(ServiceRequest request) : this()
        {
            AddErrors(request.Validate());
        }

        #endregion

        #region Properties
        [DataMember]
        public List<ValidationModel> Errors { get; set; }

        private string _message { get; set; }

        public bool HasError { get { return Errors.Any(); } }

        public string Message
        {
            get
            {
                if (HasError)
                    return string.Join("<br />", Errors.Select(i => i.Message).ToList());
                return _message;
            }
            set
            {
                _message = value;
            }
        }

        #endregion

        #region Methods
        public void AddError(string message, string member)
        {
            
            if(!string.IsNullOrWhiteSpace(message))
                Errors.Add(message, member);
        }

        public void AddErrors(List<ValidationModel> errors)
        {
            Errors.AddRange(errors);
        }

        public static implicit operator JsonResult(ServiceResponse response)
        {
            return new JsonResult() { Data = response, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        #endregion
    }
}
